﻿namespace DesignModeConsole.行为型.迭代器模式;

/// <summary>
/// 迭代器接口定义
/// </summary>
/// <typeparam name="E"></typeparam>
public interface ITerator<E>
{
    /// <summary>
    /// 是否存在下一个元素
    /// </summary>
    /// <returns></returns>
    bool HasNext();

    /// <summary>
    /// 迭代器索引往下移动一位
    /// </summary>
    void Next();

    /// <summary>
    /// 当前项
    /// </summary>
    /// <returns></returns>
    E CurrentItem();
}

/// <summary>
/// array迭代器  如果遍历的过程中修改了集合，那么就直接让报错处理
/// </summary>
/// <typeparam name="E"></typeparam>
public class ArrayIterator<E> : ITerator<E>
{
    private int _cursor;
    private readonly List<E> _list;
    private readonly int _expectedModCount;

    public ArrayIterator(List<E> list)
    {
        this._cursor = 0;
        this._list = list;
        _expectedModCount = list.Count;
    }

    public bool HasNext()
    {
        CheckForComodification();
        return _cursor >= 0 && _cursor < _list.Count;
    }

    public void Next()
    {
        CheckForComodification();
        _cursor++;
    }

    public E CurrentItem()
    {
        CheckForComodification();
        if (_cursor >= _list.Count)
            throw new IndexOutOfRangeException("索引超出界限");

        return _list[_cursor];
    }

    /// <summary>
    /// 检查集合是否被修改了
    /// </summary>
    /// <exception cref="ArgumentException"></exception>
    private void CheckForComodification()
    {
        if (_list.Count != _expectedModCount)
            throw new ArgumentException("集合已经被修改");
    }
}